import { Component, OnInit } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { filter } from 'lodash-es';
import { CallService } from '../call.service';


@Component({
  selector: 'app-select-dir',
  templateUrl: './select-dir.page.html',
  styleUrls: ['./select-dir.page.scss'],
})
export class SelectDirPage implements OnInit {
  dirs = [];
  paths = [];
  selected = '';
  selectPath = '';
  constructor(
    private callService: CallService,
    private modalCtrl: ModalController,
  ) {
    this.selected = '';
  }

  get path() { return this.selectPath; }

  set path(path: string) {
    this.selectPath = path;
    this.paths = filter(path.split('/'), d => d);
    // 加载目录列表
    this.ls(path);
  }

  async ls(path: string) {
    this.dirs = await this.callService.call('ls', {
      def: [
        { name: 'a', formatTime: '2020-01-01 12:12:12' },
        { name: 'bb', formatTime: '2020-01-01 12:12:12' },
        { name: 'test', formatTime: '2020-01-01 12:12:12' },
      ]
    }, path);
  }


  async ngOnInit() {
    this.path = await this.callService.call('pwd', { def: '/tmp/a' });
  }

  close() {
    this.modalCtrl.dismiss();
  }

  select(dir: string) {
    console.log('selected', dir);
    if (this.selected !== dir) {
      this.selected = dir;
      return;
    }

    this.path = `${this.path}/${this.selected}`;
    this.selected = '';
  }

  open(i: number) {
    this.path = `/${this.paths.slice(0, i + 1).join('/')}`;
  }

  ok() {
    this.modalCtrl.dismiss({
      dir: `${this.path}/${this.selected}`,
    });
  }
}
